<?php

namespace App\Http\Middleware;

use Carbon\Carbon;
use Closure;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;

class AuthBox
{
    protected $timeError = 120;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next,$role=null)
    {
        try {
            //必须是在时间范围内，并且签名校验成功
            if(!auth()->guard('box')->guest()){
                return $next($request);
            }else{
                return ajax_output(301,"请先登录");
            }
        } catch (\Exception $e) {
            return ajax_output(300,"权限不足:".$e->getMessage());
        }
        //todo 判断权限

        return $next($request);
    }

    /**
     * 判断用户请求是否在对应时间范围
     *
     * @author tubage
     * @param \Illuminate\Http\Request $request
     * @return boolean
     */
    protected function allowTimestamp($request)
    {
        $queryTime = Carbon::createFromTimestamp($request->header('timestamp', 0));
        $lfTime = Carbon::now()->subSeconds($this->timeError);
        $rfTime = Carbon::now()->addSeconds($this->timeError);
        if ($queryTime->between($lfTime, $rfTime, true)) {
            return true;
        }
        return false;
    }

    /**
     * 验证签名
     * @param $data
     * @param $sign
     * @return bool
     */
    protected function checkSign($timestamp="",$sign=""){
        if(strtoupper(md5("SC.".$timestamp.".SC"))==$sign){
            return true;
        }
        return false;
    }
}
